package com.ruoyi.project.system.auth.controller;

import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.system.auth.domain.SysAuth;
import com.ruoyi.project.system.auth.service.AuthService;
import org.apache.commons.io.FileUtils;
import org.pac4j.core.config.Config;
import org.pac4j.saml.client.SAML2Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author renzhihao
 * @date 2023/03/27 11:00
 */
@DependsOn("ruoYiConfig")
@RestController
public class Pac4jController {

    @Autowired
    private Config config;

    @Autowired
    private AuthService authService;

    @ResponseBody
    @RequestMapping(value = "/sp/metadata/{clientName}", produces = MediaType.APPLICATION_XHTML_XML_VALUE)
    public String metadata(@PathVariable String clientName) throws IOException {
        final SAML2Client client = (SAML2Client) config.getClients()
                .findClient(clientName).orElse(null);
        if (client == null) {
            return null;
        }

        SysAuth sysAuth = authService.getAuthWayByClientName(clientName);
        if (sysAuth == null) {
            return null;
        }

        client.init();

        String localPath = RuoYiConfig.getProfile() + "/saml/";
        return FileUtils.readFileToString(new File(localPath + sysAuth.getMetadataFilename()), StandardCharsets.UTF_8);
    }
}
